package com.firstgroup.dms.controller;

import com.firstgroup.dms.common.Result;
import com.firstgroup.dms.pojo.User;
import com.firstgroup.dms.service.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Api(value = "管理员表(User)", tags = "管理员表(User)接口API")
public class UserController {
    @Resource
    private UserServiceImpl userServiceImpl;

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam String username,
            @RequestParam String password,
            HttpSession session) {
        try {
            // 验证用户名密码
            User user = userServiceImpl.login(username, password);
            if (user != null) {
                // 登录成功，将用户信息存入session
                session.setAttribute("yongHu", user);
                return Result.success();
            }
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @GetMapping("/logout")
    public Result logout(HttpSession session) {
        try {
            // 清除session
            session.removeAttribute("yongHu");
            return Result.success();
        } catch (Exception e) {
            return Result.error("退出失败：" + e.getMessage());
        }
    }

    @PostMapping("/changePwd")
    public Result changePwd(@RequestParam String oldPassword,
            @RequestParam String newPassword,
            HttpSession session) {
        try {
            User user = (User) session.getAttribute("yongHu");
            if (user == null) {
                return Result.error("请先登录");
            }

            String username = user.getUserName();
            System.out.println("当前用户名：" + username);
            System.out.println("原密码：" + oldPassword);
            System.out.println("新密码：" + newPassword);

            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户信息异常");
            }

            return userServiceImpl.changePwd(username, oldPassword, newPassword);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }
}
